package es.xpt.ysf.commons.report;

import java.util.Locale;

import es.xpt.ysf.logging.LogManager;

/**
 * @author joseluis.vinuales
 * 
 */
public class FieldValueGetter {
	public static Object getValue(Object target, String property) {
		int index = property.indexOf(".");
		if (index != -1) {
			target = getFieldValue(target, property.substring(0, index));

			return target != null ? getValue(target, property.substring(index + 1)) : null;
		} else {
			return target != null ? getFieldValue(target, property) : null;
		}
	}

	private static Object getFieldValue(Object target, String property) {
		try {
			property = convertToGetter(property);
			java.lang.reflect.Method method = target.getClass().getMethod(property);

			return method.invoke(target);
		} catch (Exception e) {
			LogManager.getLog(FieldValueGetter.class).error(e.getMessage(), e);
		}

		return null;
	}

	private static String convertToGetter(String property) {
		StringBuffer buf = new StringBuffer();
		buf.append("get");
		buf.append(property.substring(0, 1).toUpperCase(Locale.getDefault()));
		buf.append(property.substring(1));

		return buf.toString();
	}
}